﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace POSPlus.DatabaseOperations
{
	/// <summary>
	/// Executes a query on a database that designed to return rows.
	/// </summary>
	/// <remarks>
	/// This class has been depreciated: Extend the DatabaseObject class to access specific information.
	/// </remarks>
	public class DatabaseQueryExecutor : DatabaseOperationExecutor
	{
		#region Properties
		public DataRow Current
		{
			get
			{
				if (_currentRecord < 0)
					if (_records.Rows.Count > 0)
						return _records.Rows[0];
					else
						return null;
				else
					return _records.Rows[_currentRecord];
			}
		}
		public override int RecordCount
		{
			get { return _records.Rows.Count; }
		}
		#endregion

		#region Members
		private DataTable _records;
		private int _currentRecord;
		private string connectionString;
		#endregion

		#region Constructors
		public DatabaseQueryExecutor(String server, String user, String password, String database)
			: base(server, user, password, database)
		{
			_records = new DataTable();
			_currentRecord = -1;
		}

		public DatabaseQueryExecutor(string connectionString) : base(connectionString)
		{
			_records = new DataTable();
			_currentRecord = -1;
		}
		#endregion

		#region Methods
		public override void Execute()
		{
			if (CommandString == null)
				throw new NullReferenceException("The CommandString cannot be null");

			_records = new DataTable();
			_currentRecord = -1;

			try
			{
				_connectionManager.Open();
			}
			catch (InvalidOperationException ex)
			{
				//_connectionManager.Connection.ConnectionString = _connectionManager.ToString();
				//_connectionManager.Open();
				throw new InvalidOperationException("Unable to open SQL connection: " + ex.Message);
			}
			catch (SqlException ex)
			{
				throw ex;
			}

			using (SqlDataAdapter adapter = new SqlDataAdapter(CommandString, _connectionManager.Connection))
			{
				try
				{
					adapter.Fill(_records);
				}
				catch (InvalidOperationException ex)
				{
					throw new InvalidOperationException("Execution of query failed: " + ex.Message);
				}
				catch (SqlException ex)
				{
					throw ex;
				}

				Close();
			}
		}

		public DataRow Next()
		{
			if (HasNext())
			{
				_currentRecord++;
				return Current;
			}
			else
			{
				throw new IndexOutOfRangeException();
			}
		}

		public DataRow Get(int index)
		{
			if (index < _records.Rows.Count && index >= 0)
				return _records.Rows[index];
			else
				throw new IndexOutOfRangeException();
		}

		public bool HasNext()
		{
			return _currentRecord + 1 < _records.Rows.Count;
		}
		#endregion
	}
}
